package com.nus.database;

import com.nus.beans.User;
import com.nus.database.util.DataReadUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by IntelliJ IDEA.
 * User: dell
 * Date: 9/15/12
 * Time: 11:39 PM
 * To change this template use File | Settings | File Templates.
 */
public class LoginDBManager extends DBManager {
    public LoginDBManager(Connection connection) {
        super(connection);
    }

    public boolean login(String loginName, String password) {
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        boolean isValidLogin = false;
        try {
            statement = connection.prepareStatement(SQLStatements.LOGIN_SQL);
            statement.setString(1, loginName);
            statement.setString(2, password);
            resultSet = statement.executeQuery();

            if (resultSet.next()) {
                isValidLogin = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        } finally {
            close(statement, resultSet);
        }
        return isValidLogin;
    }

    public User getUser(String loginName) {
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        User user = null;
        try {
            statement = connection.prepareStatement(SQLStatements.USER_DATA_BY_LOGIN_NAME_SQL);
            statement.setString(1, loginName.toUpperCase());
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                user = DataReadUtils.getUserInformation(resultSet);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        } finally {
            close(statement, resultSet);
        }
        return user;
    }

    @Override
    protected void finalize() throws Throwable {
        //do nothing
    }
}
